'use strict';

const Service = require('egg').Service;
const API = require('../../api');

class WechatApiService extends Service {
  /**
   * ocrOfUrlOfIdCard
   */
  async ocrOfUrlOfIdCard(appName, url) {
    const { service } = this;
    const { wxAppToken } = service;

    const token = await wxAppToken.getToken(appName);
    if (!token) return;

    const apiRes = await API.wechat.IdCardLicense(
      {
        access_token: token
      },
      {
        img_url: url
      }
    );
    return apiRes;
  }

  /**
   * ocrOfUrlOfPrintedText
   */
  async ocrOfUrlOfPrintedText(appName, url) {
    const { service } = this;
    const { wxAppToken } = service;

    const token = await wxAppToken.getToken(appName);
    if (!token) return;

    const apiRes = await API.wechat.OcrOfPrintedText(
      {
        access_token: token
      },
      {
        img_url: url
      }
    );
    return apiRes;
  }

  /**
   * sendMinaNotice
   * @param {*} param0 sendMinaNotice
   */
  async sendMinaNotice({ wx_union_user_id, tpl_mark, data }) {
    const { service, app } = this;
    const { wxUnionUser, wxAppToken } = service;
    const { wechatApi } = app.lib;
    try {
      const user = await wxUnionUser.findOne({ id: wx_union_user_id });
      if (!user) throw '暂无该微信用户';
      if (!user.mina_openid) throw '暂无该微信用户 mina_open_id';

      const token = await wxAppToken.getToken('mina_rider');
      if (!token) throw '暂无token';

      const openId = [user.mina_openid];

      const res = await wechatApi.subscribeSend({
        currentToken: token,
        tplMark: tpl_mark,
        openId,
        minaPage: '/pages/index',
        tplArrData: data
      });
      console.log('微信通知发送结果', res);
      return res;
    } catch (err) {
      console.log('微信通知失败结果', err);
      return false;
    }
  }

  /**
   * 是否关注公众号
   */
  async FollowWechatFlag({ openid }) {
    const { service, app } = this;
    const { wxUnionUser, wxAppToken } = service;
    const { wechatApi } = app.lib;
    try {
      const token = await wxAppToken.getToken('public_wx');
      if (!token) throw '暂无token';

      console.log(token, 'token', openid);
      const openId = [openid];
      const res = await wechatApi.getUserInfo(token, openid);
      console.log('成功结果', res);
      return res;
    } catch (err) {
      console.log('失败结果', err);
      return;
    }
  }

  /**
   * 发送微信模板消息
   */
  async sendWxTpl(users, punishParams) {
    const { service, app } = this;
    const { wxAppToken } = service;
    const { wechatApi } = app.lib;
    try {
      const token = await wxAppToken.getToken('public_wx');
      if (!token) throw '暂无token';
      for (let i = 0; i < users.length; i++) {
        if (users[i].wx_public_user_id) {
          punishParams.admin_id = users[i].id;
          await wechatApi.publicNotice(
            token,
            users[i].wx_public_user.wx_openid,
            punishParams
          );
        }
      }
      return true;
    } catch (err) {
      console.log('失败结果', err);
      return;
    }
  }

  /**
   * 同步公众号用户表
   */
  async GetWxUserList() {
    const { service, app } = this;
    const { wxPublicUser, wxAppToken } = service;
    const { wechatApi } = app.lib;
    try {
      const token = await wxAppToken.getToken('public_wx');
      if (!token) throw '暂无token';
      const res = await this.GetOpenidFuc(token);

      for (let i = 0; i < res.length; i++) {
        const info = await wechatApi.getUserInfo(token, res[i]);
        await wxPublicUser.upsert({
          unionid: info.unionid,
          wx_openid: info.openid,
          sex: info.sex,
          nickname: info.nickname,
          mobile: info.mobile,
          subscribe: info.subscribe
        });
      }
      return res;
    } catch (err) {
      console.log('失败结果', err);
      return;
    }
  }
  // 递归获取数据
  async GetOpenidFuc(token) {
    const { service, app } = this;
    const { wxUnionUser, wxAppToken } = service;
    const { wechatApi } = app.lib;
    let openidArr = [];
    let next_openid = '';
    const func = async () => {
      const res = await wechatApi.getOpenidList(token, next_openid);
      if (!res) throw '出错';
      openidArr = openidArr.concat(res.openid);
      next_openid = res.next_openid ? res.next_openid : '';
      if (next_openid) await func();
    };
    await func();
    return openidArr;
  }
}

module.exports = WechatApiService;
